package com.study.Caro;

import java.util.concurrent.locks.ReentrantLock;

import com.study.GameService.NetConnection.GameService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;

@SuppressLint("HandlerLeak")
public class Caro extends Activity {
    /** Called when the activity is first created. */
	
	/*=====================attribute========================*/
	public static final int GAME_MSG = 0;
	public static final int CHAT_MSG = 1;
	public static final int INFO_MSG = 2;
	
	//public Handler mReceiver;
	public Screen screen;
	private Brain brain;
	private int play_mode = GameService.SERVER_MODE;
	int mPosX = 0, mPosY = 0;
	String mChat, mInfo;
	private CountDownTimer countDown;
	/*======================================================*/
	
	/*=======================method=========================*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.caro);
        play_mode = getIntent().getIntExtra("MODE", 0);
        
        screen = (Screen)findViewById(R.id.screen);
        brain = Brain.GetInstance();
        
        GameService game = GameService.GetInstance(play_mode, null);
        game.SetReceiver(mReceiver);
        
        TextView turn = (TextView)findViewById(R.id.textTurn);
    	String sTurn = "Opposite's turn";
    	if(brain.IsMyTurn()){
    		sTurn = "Your turn";
    	}
    	turn.setText(sTurn);
    	
    	// Initiate timeout counter
    	final TextView timout = (TextView)findViewById(R.id.txtTimeOut);
    	countDown = new CountDownTimer(Brain.TIMEOUT, 1000) {

    		public void onTick(long millisUntilFinished) {
    			String remain = Integer.toString((int)millisUntilFinished / 1000);
    			timout.setText(remain);
    		}

    		public void onFinish() {
    			final ReentrantLock lock = brain.GetLock();
				// Get lock to change gameToken state
    			lock.lock();
    			if(brain.IsMyTurn()){
    				UpdateScreenTimeOut(true);
    			}
    			lock.unlock();
    		}
    	};
    	countDown.start();
    }
    
    private Handler mReceiver = new Handler(){
    	@Override
    	public void handleMessage(Message msg) {
    		String message = (String)msg.obj;
    		int msgType = PaserMessage(message);
    		if(msgType == GAME_MSG){
    			UpdateScreen(mPosX, mPosY);
    			brain.UpdateState(mPosX, mPosY, false);
    			/*-----------------UPDATE LEN SCREEN------------------*/
        		screen.update_screen();
    		}else if(msgType == INFO_MSG){
    			if(mInfo.equals("Quit")){
    				GameService game = GameService.GetInstance(0, null);
    				game.QuitGame();
    				Caro.this.finish();
    			}else if(mInfo.equals("TIMEOUT"))
    				UpdateScreenTimeOut(false);
    		}
    		super.handleMessage(msg);
    	}
    };
    
    public void UpdateScreen(int posX, int posY){
    	TextView turn = (TextView)findViewById(R.id.textTurn);
    	String sTurn = turn.getText().toString().equals("Opposite's turn") ? 
    			"Your turn" : "Opposite's turn";
    	turn.setText(sTurn);
    	
    	// Update count down timer
    	countDown.cancel();
    	countDown.start();
    }
    
    public void UpdateScreenTimeOut(boolean myTurn){
    	UpdateScreen(0, 0);
		brain.UpdateStateTimeOut();
		if(myTurn){
			Message msg = Message.obtain();
			String timeout = "INFO:TIMEOUT";
			msg.obj = timeout;
			GameService.SendData(msg);
		}
    }

    public int PaserMessage(String response){
    	// TODO
    	// Parser message from socket to identify message type
    	// There are 2 type: 
    	// Conversation	: "CHAT:content"
    	// Game		: "GAME:posX-posY"
    	int ret = 0;
    	String[] parts = response.split(":");
    	if(parts[0].equals("GAME")){
    		ret = GAME_MSG;
    		String[] coordinates = parts[1].split("-");
    		mPosX = Integer.parseInt(coordinates[0]);
    		mPosY = Integer.parseInt(coordinates[1]);
    	}else if(parts[0].equals("CHAT")){
    		ret = CHAT_MSG;
    		mChat = parts[1];
    	}else if(parts[0].equals("INFO")){
    		ret = INFO_MSG;
    		mInfo = parts[1];
    	}
    	return ret;
    }

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		AlertDialog.Builder builder = new AlertDialog.Builder(Caro.this);
		
		builder.setMessage(" Do you really want to quit game ?")
		       .setCancelable(false)
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       })
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
						GameService game = GameService.GetInstance(0, null);
						game.QuitGame();
						Caro.super.onBackPressed();
		           }
		       });
		 builder.show();				
	}
    
    
    /*======================================================*/
}